﻿/*
 * Created by SharpDevelop.
 * User: Emanuel Santos
 * Date: 24-05-2013
 * Time: 09:12
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using Financial;

namespace Server
{
	/// <summary>
	/// Description of Server.
	/// </summary>
	public class Server
	{
		public Server()
		{
			//Criar socket do lado do servidor
			Socket socketServidor = new Socket(AddressFamily.InterNetwork,
			                                   SocketType.Stream,
			                                   ProtocolType.Tcp);

			//Criar EndPoint e admitir qualquer IP
			//Ver camada de transporte
			IPEndPoint ie = new IPEndPoint(IPAddress.Any,6000);
			
			//Associar socket ao IPEndPoint local
			socketServidor.Bind(ie);
			//Socket à escuta, no máximo 10 ligações
			socketServidor.Listen(10);

			Console.WriteLine("`•.,¸¸,.•´¯ SERVIDOR Leilao ¯`•.,¸¸,.•´\n");
			Console.WriteLine("Espera de pedidos...");

			while(true)
			{
				ConnectionThread novaConexao = new ConnectionThread();

                novaConexao.threadClient = socketServidor.Accept();

				Thread novoThread = new Thread(new ThreadStart(()=>novaConexao.HandleConnection()));
                
                novoThread.Start();
				if(novaConexao.connections>=10 || novaConexao.sessaoFechada)  {
					break;
				}
			}
			socketServidor.Close();
		}
	}
}
